package com.ruoyi.web.cq;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadUtil {
    public static void download(String targetPath, String url) throws Exception {
        download(targetPath, new URL(url));
    }

    public static void download(String targetPath, URL url) throws Exception {

        String filePath = targetPath.replace("\\", "/");
        filePath = filePath.endsWith("/") ? filePath : (filePath + "/");
        String fileName = url.toString().substring(url.toString().lastIndexOf("/") + 1);
        if (!new File(filePath+fileName).exists()){
            String tmpName = fileName + "tmp";
            int bytesum = 0;
            int byteread = 0;
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
            conn.setRequestProperty("referer", "https://www.pixiv.net/");
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(filePath + tmpName);
            byte[] buffer = new byte[1024];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            fs.flush();
            fs.close();
            new File(filePath + tmpName).renameTo(new File(filePath + fileName));
        }
    }
}
